package com.chess.connections.net;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ChessConnectionServer {

    private static final Logger logger = LoggerFactory.getLogger(ChessConnectionServer.class);

    private int port = 8050;

    private WebSocketChannelInitializer handler;

    public ChessConnectionServer(){
        ServerMessageHandler handler = new ServerMessageHandler();
        this.handler = new WebSocketChannelInitializer(handler);
    }

    public void nettyStart() throws Exception {
        logger.info("netty服务端口：{}", port);

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                //注意是childOption
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(handler);

        serverBootstrap.bind(port).sync().channel().closeFuture();

        logger.info("Netty WebSocket server listening on port {} and ready for connections...", port);
    }
}
